package com.mystyle.le.weekproject.fragment;


import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mystyle.le.weekproject.R;
import com.mystyle.le.weekproject.adapter.HeadListAdapter;
import com.mystyle.le.weekproject.asynctaks.HeadListAsyncTaks;
import com.mystyle.le.weekproject.asynctaks.HeadTitlesAsyncTaks;
import com.mystyle.le.weekproject.beans.HeadList;
import com.mystyle.le.weekproject.beans.HeadTitls;
import com.mystyle.le.weekproject.intentfactbackcall.MyCallBack;
import com.mystyle.le.weekproject.utils.ParseJson;
import com.mystyle.le.weekproject.utils.SetListViewHeight;
import com.mystyle.le.weekproject.utils.Url;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * 资讯页面的头条
 * A simple {@link Fragment} subclass.
 */
public class HeadTitleFragment extends Fragment {


    private ListView head_LV;
    private ViewPager head_VP;
    private List<View> list;
    private ImageView head_iv1,head_iv2,head_iv3,head_iv4,head_iv5,head_iv6;
    private TextView head_tv1,head_tv2,head_tv3,head_tv4,head_tv5,head_tv6;
    private List<HeadList> lists = new ArrayList<>();
    private int pageNum = 0;
    private Button head_add;
    private boolean isLast = false;
    private HeadListAdapter headListAdapter;
    //指示器图片
    private ImageView[] icons;

    private android.os.Handler handler = new android.os.Handler(){
        @Override
        public void handleMessage(Message msg) {
            head_VP.setCurrentItem(head_VP.getCurrentItem()+1);
            handler.sendEmptyMessageDelayed(1,2000);

        }
    };


    public HeadTitleFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_head_title, container, false);

        //初始化控件
        initView(view);

        //初始化数据ListView
        initListView();
        return view;
    }

    private void initListView() {
        headListAdapter = new HeadListAdapter(lists, getActivity());
        //获取尾布局
        View inflate = getActivity().getLayoutInflater().inflate(R.layout.headfoot_layout, null);
        head_add = ((Button) inflate.findViewById(R.id.head_add));
        //添加到尾部
        head_LV.addFooterView(inflate,null,true);
        new HeadListAsyncTaks(new MyCallBack.HeadListBack() {
            @Override
            public void sendBack(String path) {
                List<HeadList> headLists = ParseJson.parseHeadList(path);
                if (headLists!=null){
                    lists.addAll(headLists);
                    head_LV.setAdapter(headListAdapter);
                    SetListViewHeight.setListViewHeightBasedOnChildren(head_LV);

                }
            }
        },getActivity()).execute(Url.game_headline_path);

        //滑动事件
        head_LV.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isLast&&scrollState==SCROLL_STATE_IDLE){
                    head_add.setVisibility(View.VISIBLE);
                }else {
                    head_add.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isLast = (firstVisibleItem+visibleItemCount)==totalItemCount;
            }
        });

        head_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum++;
                new HeadListAsyncTaks(new MyCallBack.HeadListBack() {
                    @Override
                    public void sendBack(String path) {
                        List<HeadList> headLists = ParseJson.parseHeadList(path);
                        if (headLists!=null){
                            lists.addAll(headLists);
                            headListAdapter.notifyDataSetChanged();
                            SetListViewHeight.setListViewHeightBasedOnChildren(head_LV);
                        }
                    }
                },getActivity()).execute(Url.getHeadPagingPath(pageNum));
//                head_add.setVisibility(View.GONE);
            }
        });
    }


    /*
    * 初始化控件
    * */
    private void initView(View view) {
        head_LV = ((ListView) view.findViewById(R.id.head_LV));
        head_VP = ((ViewPager) view.findViewById(R.id.head_VP));
        list = new ArrayList<>();
        //找布局
        initFind();

        //设置指示器
        initIcon(view);
        head_VP.setAdapter(new MyHeadAdapter());
        //默认展示第一条
        head_VP.setCurrentItem(Integer.MAX_VALUE/2-Integer.MAX_VALUE/2%list.size());
        //使用Handler发送消息  实现轮播
        handler.sendEmptyMessageDelayed(1,2000);


        head_VP.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //设置为当前滑动的位置
               head_VP.setCurrentItem(position);
//                Log.e("AAA","==position=="+position);
                for (int i =0;i<icons.length;i++){
                    icons[i].setImageResource(R.mipmap.dot_normal);
                }
                //当前位置改变成不一样的
                 icons[position % list.size()].setImageResource(R.mipmap.dot_enable);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initFind() {
        int identifier = getActivity().getResources().getIdentifier("head_pic1", "layout", getActivity().getPackageName());
        int identifier2 = getActivity().getResources().getIdentifier("head_pic2", "layout", getActivity().getPackageName());
        int identifier3 = getActivity().getResources().getIdentifier("head_pic3", "layout", getActivity().getPackageName());
        int identifier4 = getActivity().getResources().getIdentifier("head_pic4", "layout", getActivity().getPackageName());
        int identifier5 = getActivity().getResources().getIdentifier("head_pic5", "layout", getActivity().getPackageName());
        int identifier6 = getActivity().getResources().getIdentifier("head_pic6", "layout", getActivity().getPackageName());
        View inflate = getActivity().getLayoutInflater().inflate(identifier, null);
        View inflate2 = getActivity().getLayoutInflater().inflate(identifier2, null);
        View inflate3 = getActivity().getLayoutInflater().inflate(identifier3, null);
        View inflate4 = getActivity().getLayoutInflater().inflate(identifier4, null);
        View inflate5 = getActivity().getLayoutInflater().inflate(identifier5, null);
        View inflate6 = getActivity().getLayoutInflater().inflate(identifier6, null);
        //初始化控件并赋值
        initHeadView(inflate);
        initHeadView2(inflate2);
        initHeadView3(inflate3);
        initHeadView4(inflate4);
        initHeadView5(inflate5);
        initHeadView6(inflate6);
        list = new ArrayList<>();
        list.add(inflate);
        list.add(inflate2);
        list.add(inflate3);
        list.add(inflate4);
        list.add(inflate5);
        list.add(inflate6);
    }

    class MyHeadAdapter extends PagerAdapter{
        @Override
        public int getCount() {
//            return list.size();
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
//            container.addView(list.get(position));
//            return list.get(position);
            int i = position % list.size();
            container.addView(list.get(i));
            return list.get(i);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            container.removeView(list.get(position));
            int i = position % list.size();
            container.removeView(list.get(i));
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    private void initHeadView6(View inflate6) {
        head_iv6 = ((ImageView) inflate6.findViewById(R.id.head_iv6));
        head_tv6 = ((TextView) inflate6.findViewById(R.id.head_tv6));
       downData(5,head_tv6,head_iv6);
    }

    private void initHeadView5(View inflate5) {
        head_iv5 = ((ImageView) inflate5.findViewById(R.id.head_iv5));
        head_tv5 = ((TextView) inflate5.findViewById(R.id.head_tv5));
       downData(4,head_tv5,head_iv5);
    }

    private void initHeadView4(View inflate4) {
        head_iv4 = ((ImageView) inflate4.findViewById(R.id.head_iv4));
        head_tv4 = ((TextView) inflate4.findViewById(R.id.head_tv4));
        downData(3,head_tv4,head_iv4);
    }

    private void initHeadView3(View inflate3) {
        head_iv3 = ((ImageView) inflate3.findViewById(R.id.head_iv3));
        head_tv3 = ((TextView) inflate3.findViewById(R.id.head_tv3));
        downData(2,head_tv3,head_iv3);
    }

    private void downData(final int i, final TextView tv, final ImageView iv) {
        new HeadTitlesAsyncTaks(new MyCallBack.HeadBack() {
            @Override
            public void sendBack(List<HeadTitls> list) {
                HeadTitls headTitls = list.get(i);
                tv.setText(headTitls.getTitle());
                String l_picture = headTitls.getL_picture();
                Picasso.with(getActivity()).load(l_picture).into(iv);
            }
        },getActivity()).execute(Url.game_headline_path);
    }

    private void initHeadView2(View inflate2) {
        head_iv2 = ((ImageView) inflate2.findViewById(R.id.head_iv2));
        head_tv2 = ((TextView) inflate2.findViewById(R.id.head_tv2));
       downData(1,head_tv2,head_iv2);
    }

    private void initHeadView(View inflate) {
        head_iv1 = ((ImageView) inflate.findViewById(R.id.head_iv1));
        head_tv1 = ((TextView) inflate.findViewById(R.id.head_tv1));
       downData(0,head_tv1,head_iv1);
    }

    private void initIcon(View view) {
        LinearLayout layout = ((LinearLayout) view.findViewById(R.id.layout_id1));
        icons = new ImageView[list.size()];
        for (int i =0;i<list.size();i++){
            icons[i] = new ImageView(getActivity());
            //设置图片的属性
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20,20);
            params.setMargins(0,0,20,0);
            icons[i].setLayoutParams(params);
            //将指示器添加到容器中
            layout.addView(icons[i]);
            icons[i].setImageResource(R.mipmap.dot_normal);//设置图片
            icons[i].setTag(i);//保存当前位置
            icons[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    head_VP.setCurrentItem((Integer) v.getTag(),false);
                }
            });
            icons[i].setImageResource(R.mipmap.dot_normal);
        }
    }

}
